<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--用户数据-->
      <el-col :span="24" :xs="24">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
                       v-hasPermi="['system:user:add']">批量创建激活码
            </el-button>
          </el-col>
<!--          <el-col :span="1.5">
            <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate"
                       v-hasPermi="['system:user:edit']">修改
            </el-button>
          </el-col>-->
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
                       v-hasPermi="['system:user:remove']">删除
            </el-button>
          </el-col>
<!--          <el-col :span="1.5">
            <el-button type="info" icon="el-icon-upload2" size="mini" @click="handleImport"
                       v-hasPermi="['system:user:import']">导入
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-dropdown placement="bottom">
              <el-button type="warning" icon="el-icon-download" size="mini" v-hasPermi="['system:user:export']">导出
              </el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item>全部页</el-dropdown-item>
                <el-dropdown-item divided>当前行</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="codeList"></right-toolbar>-->
        </el-row>

        <el-table v-loading="loading" :data="codeList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center"/>
          <el-table-column label="序号" align="center" type="index"/>
          <el-table-column label="激活码数量" align="center" prop="quantity" :show-overflow-tooltip="true"/>
          <el-table-column label="创建时间" align="center" prop="createTime">
            <template slot-scope="scope">
              <span>{{ parseTime(new Date(scope.row.createTime))}}</span>
            </template>
          </el-table-column>
          <el-table-column label="包含权限" align="center" prop="products" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span style="color: #1c84c6;cursor: pointer"
                    @click="checkProducts(scope.row)">{{ scope.row.products }}</span>
            </template>
          </el-table-column>
          <el-table-column label="时效(天)" align="center" prop="segment" :show-overflow-tooltip="true"/>
          <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true"/>
          <el-table-column label="操作" align="center" prop="isActive" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)"
                         v-hasPermi="['system:user:edit']">查看详情
              </el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                         v-hasPermi="['system:user:edit']">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                    @pagination="getCodeList"/>
      </el-col>
    </el-row>

    <!-- 新增或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body center>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="创建数量" prop="quantity">
              <el-input v-model="form.quantity" placeholder="请输入创建数量"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="时效(天)" prop="segment">
              <el-input v-model="form.segment" placeholder="请输入时效(天)"/>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="20">
            <el-form-item label="激活程序选择" prop="productIds">
              <el-select v-model="form.productIds" multiple placeholder="请选择">
                <el-option
                  v-for="item in list"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" placeholder="备注"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm">创 建</el-button>
          <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!--  查看详情  -->
    <el-dialog
      title="提示"
      width="80%"
      :visible.sync="dialogVisible"
      >
      <!--用户数据-->
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button type="primary" icon="el-icon-download" size="mini" @click="handleExport"
                     v-hasPermi="['system:user:remove']">导出
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="success" icon="el-icon-check" size="mini" :disabled="activationmultiple"
                     @click="handleActivation"
                     v-hasPermi="['system:user:remove']">批量激活
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button type="warning" icon="el-icon-close" size="mini" :disabled="activationmultiple"
                     @click="handleFrozen"
                     v-hasPermi="['system:user:edit']">批量冻结
          </el-button>
        </el-col>
      </el-row>
      <el-table v-loading="loading" :data="detailData" @selection-change="handleActivationChange">
        <el-table-column type="selection" width="50" align="center"/>
        <el-table-column label="序号" align="center" type="index"/>
        <el-table-column label="激活码" width="630" align="center" prop="code">
          <template slot-scope="scope">
            <span>{{scope.row.code}}</span>
          </template>
        </el-table-column>
        <el-table-column label="权限" align="center" prop="products">
          <template slot-scope="scope">
            <span style="color: #1c84c6;cursor: pointer" @click="checkProducts(scope.row)">{{ scope.row.products }}</span>
          </template>
        </el-table-column>
        <el-table-column label="时效" align="center" prop="segment" :show-overflow-tooltip="true"/>
        <el-table-column label="是否激活" align="center" prop="status" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <span>{{ scope.row.status === 'APPLIED' ? '是' : '否'}}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button v-if="scope.row.status === 'AVAILABLE'" size="mini" type="text" icon="el-icon-close" @click="handleFrozen(scope.row)"
                       v-hasPermi="['system:user:edit']">冻结
            </el-button>
            <el-button v-else size="mini" type="text" icon="el-icon-check"
                       @click="handleActivation(scope.row)" v-hasPermi="['system:user:remove']">激活
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="detailDataTotal>0" :total="detailDataTotal" :page.sync="detailDataParams.pageNum"
                  :limit.sync="detailDataParams.pageSize"
                  @pagination="getDetailData(batchId)"/>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="dialogVisible = false">确 定</el-button>
  </span>
    </el-dialog>


<!--    根据权限数量查看具体权限-->
    <el-dialog
      title="包含权限"
      :visible.sync="productsDilog"
      width="20%"
      >
      <ul>
        <li v-for="(item, index) in productsList" :key="index">
            {{item.name}}
        </li>
      </ul>
      <span slot="footer" class="dialog-footer">
    <el-button type="primary" @click="productsDilog = false">关 闭</el-button>
  </span>
    </el-dialog>

  </div>
</template>

<script>
  import {
    importTemplate,
  } from "@/api/system/user";
  import {codeList, delUser, addCode, detailCode, exportUser, activation, chcekProducts} from "@/api/code"
  import {listData} from "@/api/index/index"
  import {getToken} from "@/utils/auth";

  export default {
    name: "User",
    data() {
      return {
        productsDilog: false, //权限弹框
        productsList: [], //具体的权限
        detailData: [], //查看详情列表
        batchId: '',
        list: [], //新增程序列表
        codeList: [], //列表
        dialogVisible: false, //详情
        isIndeterminate: true,
        // 遮罩层
        loading: true,
        activationsingle: true,
        activationmultiple: true,
        activationIds: [],
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        detailDataTotal: 0, //查看详情列表条数
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 表单参数
        form: {
          quantity: '',
          segment: '',
          productIds: [],
          remark:''
        },
        defaultProps: {
          children: "children",
          label: "label",
        },
        detailDataParams: {
          pageNum: 1,
          pageSize: 10,
        },
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
        },
        // 表单校验
        rules: {
          quantity: [
            {required: true, message: "创建数量不能为空", trigger: "blur"},
          ],
          segment: [
            {required: true, message: "时效不能为空", trigger: "blur"},
          ],
          productIds: [
            {required: true, message: "激活程序不能为空", trigger: "blur"},
          ]
        },
      };
    },
    watch: {},
    created() {
      this.getCodeList()
      this.getListData()
    },
    methods: {
      //根据数量查看具体权限
      checkProducts(row) {
        console.log(row,'???')
        const batchId = row.batchId || row.id
        this.productsDilog = true
        chcekProducts(batchId).then(resp => {
          let { code, data } = resp
          if(code === 200) {
            this.productsList = data
          }
        })
      },
      handleDetail(row) {
        this.batchId = row.id
        this.reset();
        this.dialogVisible = true;
        this.title = "查看详情";
        this.getDetailData(row.id)
      },
      getDetailData(id) {
        let { pageSize, pageNum } = this.detailDataParams
        let parm = {
          id: id,
          pageSize: pageSize,
          pageNum: pageNum
        }
        detailCode(parm).then(resp => {
          let {code, rows, total} = resp
          if (code === 200) {
            this.detailData = rows
            this.detailDataTotal = total
          }
        })
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {};
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.page = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map((item) => item.id);
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.open = true;
        this.title = "批量创建激活码";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.dialogVisible = true;
        this.title = "查看详情";
      },
      /** 提交按钮 */
      submitForm: function () {
        this.$refs["form"].validate((valid) => {
          if (valid) {
            addCode(this.form).then((response) => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getCodeList();
                this.reset()
              }
            });
          }
        });
      },
      // 批量激活多选
      handleActivationChange(selection) {
        this.activationIds = selection.map((item) => {
          return {id: item.id, status: 'AVAILABLE'}
        });
        this.activationsingle = selection.length != 1;
        this.activationmultiple = !selection.length;
      },
      //批量激活
      handleActivation(row) {
        console.log(row)
        let parms = {}
        if (row.id) {
          parms = {
            activationCodeDetails: [{id: row.id, status: 'AVAILABLE'}]
          }
        } else {
          parms = {
            activationCodeDetails: this.activationIds.map(item => {
              return {id: item.id, status: 'AVAILABLE'}
            })
          }
        }
        console.log(parms)
        this.$confirm(
          '是否确认激活选中的激活码?',
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(function () {
            return activation(parms);
          })
          .then(() => {
            this.getDetailData(this.batchId)
            this.msgSuccess("激活成功");
          })
          .catch(function () {
          });
      },

      //批量冻结
      handleFrozen(row) {
        console.log(row)
        let parms = {}
        if (row.id) {
          parms = {
            activationCodeDetails: [{id: row.id, status: 'APPLIED'}]
          }
        } else {
          parms = {
            activationCodeDetails: this.activationIds.map(item => {
              return {id: item.id, status: 'APPLIED'}
            })
          }
        }
        console.log(parms)
        this.$confirm(
          '是否确认冻结选中的激活码?',
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(function () {
            return activation(parms);
          })
          .then(() => {
            this.getDetailData(this.batchId)
            this.msgSuccess("冻结成功");
          })
          .catch(function () {
          });
      },

      /** 删除按钮操作 */
      handleDelete(row) {
        const userIds = row.id || this.ids;
        this.$confirm(
          '是否确认删除激活码编号为"' + userIds + '"的数据项?',
          "警告",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(function () {
            return delUser(userIds);
          })
          .then(() => {
            this.getCodeList();
            this.msgSuccess("删除成功");
          })
          .catch(function () {
          });
      },
      /** 导出按钮操作 */
      handleExport() {
        let ids = []
        this.detailData.forEach(item => {
          ids.push(item.id)
        })
        let parms = {
          batchId: this.batchId,
          ids: ids
        }
        this.$confirm("是否确认导出用户数据项?", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(function () {
            return exportUser(parms);
          })
          .then((response) => {
            this.download(response.msg);
          })
          .catch(function () {
          });
      },
      getListData() {
        listData().then(resp => {
          let {code, data} = resp
          if (code === 200) {
            this.list = data
          }
        })
      },
      // 提交上传文件
      submitFileForm() {
        this.$refs.upload.submit();
      },
      handleClose() {
      },
      //激活码
      getCodeList() {
        codeList().then(resp => {
          let {code, rows, total} = resp
          if (code === 200) {
            this.codeList = rows
            this.total = total
            this.loading = false
          }
        })
      },
    },
  };
</script>

<style scoped>
  ul, li {
    list-style: none;
  }
</style>
